package com.maimao.zuul.service;

import com.maimao.core.constant.Constants;
import com.maimao.core.constant.RedisKeys;
import com.maimao.core.utils.CookieUtil;
import com.maimao.core.utils.Oauth2Util;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@Service
public class AuthService {

    public String getJwtFromHeader(HttpServletRequest request) {
        //取出头信息
        String authorization = request.getHeader("Authorization");
        if (StringUtils.isEmpty(authorization)) {
            return null;
        }
        if (!authorization.startsWith("Bearer ")) {
            return null;
        }
        //取到jwt令牌
        String jwt = authorization.substring(7);
        return jwt;


    }

    public String getTokenFromCookie(HttpServletRequest request, String key) {
        Map<String, String> cookieMap = CookieUtil.getCookie(request, key);
        String access_token = cookieMap.get(key);
        if (StringUtils.isEmpty(access_token)) {
            return null;
        }
        return access_token;
    }

    /**
     * 查询(jti短)令牌的有效期
     *
     * @param access_token
     * @return
     */
    public boolean isExpire(String access_token) {
        //key
        String key = RedisKeys.USER_TOKEN + access_token;
        Long expire = stringRedisTemplate.getExpire(key, TimeUnit.SECONDS);
        return expire == null || expire < 0;
    }

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    /**
     * 校验web端重复登录
     * 问题：如果前端清楚了cookie，但redis中登录信息没有失效
     */
    public boolean checkRepeat(String jwt, String access_token) {
        Map<String, Object> map = Oauth2Util.getJwtClaimsFromJwt(jwt);
        String id = (String) map.get("id");
        String type = (String) map.get("type");

        if (id != null && !StringUtils.isEmpty(type)) {
            String key = String.format(RedisKeys.REPEAT_LOGIN, id, type);
            String oldValue = stringRedisTemplate.opsForValue().get(key);
            if (StringUtils.isEmpty(oldValue)) {
                return false;
            }
            if (!oldValue.equals(access_token)) {
                //非最新的登录
                stringRedisTemplate.opsForValue().set(key, access_token, 43200, TimeUnit.SECONDS);
                return false;
            }
            return true;
        }
        return false;
    }
}
